import axios from 'axios';
import { Message } from 'element-ui';
import { redashBaseUrl } from '../../config/env';

const redash = redashBaseUrl + 'api/';

const apiUrls = {
  datasources: redash + 'data_sources',
  schema: (dataSourceId) => {
    return `${redash}data_sources/${dataSourceId}/schema`;
  },
  query: {
    queryResult: redash + 'query_results',
    byId: (queryResultId) => {
      return `${redash}query_results/${queryResultId}`;
    }
  },
  job: {
    byId: (jobId) => {
      return `${redash}jobs/${jobId}`;
    }
  }
}

const JobStatus = {
  waiting: 1,
  processing: 2,
  done: 3,
  failed: 4
}
export class RedashService{

  http = axios;

  queryResult(param){
    return this.http.post(apiUrls.query.queryResult, param);
  }

  getSchema(dataSourceId){
    return this.http.get(apiUrls.schema(dataSourceId));
  }

  getDataSources(){
    return this.http.get(apiUrls.datasources);
  }

  queryResultById(queryResultId) {
    return this.http.get(apiUrls.query.byId(queryResultId));
  }

  translateByVar(str , variables){
    str = str.replace(/\$\{([a-zA-Z\d_]+)\}/g , (match , key) => {
      if(variables[key]){
  
       let names = key;
       let datas = variables;
  
       return names.split('.').reduce((prev , curr) => {
         return prev ? prev[curr] : '';
       } , datas);
  
      }else{
        return '';
      }
    })
    return str;
  }

  job(jobId) {

    return this.http.get(apiUrls.job.byId(jobId)).then(
      res => {
        let data = res.data;
        if(data.job.status === JobStatus.done){
          return data.job;
        }else if(data.job.status == JobStatus.failed){
          Message({
            type: 'error',
            message: data.job.error
          });
          return null;
        }else{
          return this.job(jobId);
        }
      }
    );


  }

  mapQueryResult(res){
    if(res && res['query_result']){
      return {
        error: false,
        data: res['query_result']['data']['rows'],
        columns: res['query_result']['data']['columns']
      }
    }else{
      return {
        error: true,
        msg: '获取数据失败'
      }
    }
  }

  loadRedashData(param , variables){
    let query ;
    let data_source_id;
    
    if(param.expression){
      query = this.translateByVar(param.expression , variables);
      data_source_id= param.dataSource.id
    }else{
      query = param;
      data_source_id= JSON.parse(param).params.dataSource.id
    }
    
    let requestBody = {
      data_source_id: data_source_id,
      max_age: 0,
      query: query
    };

    console.log(requestBody);

    return this.queryResult(requestBody).then(
      res => {
        return this.job(res.data['job']['id']).then(
          jobData => {
            if(jobData && jobData.status === JobStatus.done){
              return this.queryResultById(jobData.query_result_id).then(
                resData => {
                  return this.mapQueryResult(resData.data);
                }
              )
            }else{
              return this.mapQueryResult(null);
            }
          }
        )
      }
    )
    // return new Promise((resolve , reject) => {

    // })
  }

}





export const redashService = new RedashService;